package com.tbit.uqbike.webmanager.util;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//用户请使用UTF-8作为源码文件的保存格式，避免出现乱码问题
@Slf4j
public class APIStore {
    /**
     * HTTP的Post请求方式
     *
     * @param strUrl 访问地址
     * @param param  参数字符串
     */
    public static String doPost(String strUrl, String param) {
        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;

        try {
            url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST"); // post方式
            httpURLConnection.connect();
            //System.out.println("ResponseCode:" + httpURLConnection.getResponseCode());
            //POST方法时使用
            byte[] byteParam = param.getBytes("UTF-8");
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.write(byteParam);
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }


    //将map型转为请求参数型
    public static String urlencode(Map<String, Object> data) {
        StringBuilder apistore = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                apistore.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                log.error(e.getMessage(), e);
            }
        }
        return apistore.toString();
    }

    // 发起请求,获取内容
    public static void main(String[] args) {
        //请求地址
        String url = "http://sim.tbit.com.cn/identity/polling.do";

        Map params = new HashMap();
        params.put("serNo", "UQ-889");
//        params.put("machineNo","003421069");
//        params.put("type","0");
        params.put("serial", "d6c91bd3-cea3-4043-ab15-a3036ef861b6");
        params.put("secret", "tbit-uqbike-uqbike-tbit-uqbike-bit-00369696");

        String result = doPost(url, urlencode(params));
        //输出结果
        System.out.println(result);
    }

}